import {coreApi} from '../apis/core-util'
import TimeStore from 'lib/stores/time-store'
import _ from 'underscore'
import moment from 'moment'

export default class List {
  constructor(props, container) {
    this.container = container;
    this.$state = {
      list: {
        loading: true
      },
      listLimit: 10,
      listOffset: 0
    };

    this.listApi = coreApi({
      size: 1,
      sm: 1,
      offset: () => this.$state.listOffset,
      limit: () => this.$state.listLimit,
      classify: 'measurementname',
      urlName: 'activitytracesimilar'
    }, TimeStore.getValue);
  }

  $load() {
    this.$state.listOffset = 0;
    return this.listApi.fetch().done((json, params) => {
      this.parseData(json);
      this.container.emit();
    });
  }

  convertData(json) {
    return _.chain(json.result).map((item) => {
      return {
        name: item.key.name,
        nameId: item.key.nameId,
        avg: item.data[0].avg,
        sm: item.data[0].sm,
        count: item.data[0].count,
        lastTime: item.data[0].lastTime
      };
    }).value();
  }

  parseData(json) {
    let data = this.convertData(json);
    this.$state.list = {
      data: data
    };
    this.$state.list.hasMore = this.$state.listLimit === data.length;
    this.$state.listOffset += data.length;

    this.$state.list.showMore = () => {
      let deferred = $.Deferred();
      this.listApi
          .fetch()
          .fail(deferred.reject)
          .done(innerJson => {
            let convertedData = this.convertData(innerJson);
            this.$state.listOffset += convertedData.length;
            deferred.resolve({
              data: convertedData,
              hasMore: this.$state.listLimit === convertedData.length
            });
          });

      return deferred.promise();
    };
  } // end parseData
}
